package org.budo.elasticsearch.jdbc.driver.statement;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.budo.elasticsearch.jdbc.driver.BudoElasticsearchJdbcConnection;
import org.budo.elasticsearch.jdbc.driver.BudoElasticsearchJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.jdbc.driver.statement.AbstractJdbcStatement;
import org.budo.support.lang.util.MapUtil;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;

import com.carrotsearch.hppc.ObjectLookupContainer;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;

/**
 * @author limin
 */
public class SHOW_TABLE_STATUS extends AbstractJdbcStatement {
    public SHOW_TABLE_STATUS(String sql) {
        this.setSql(sql);
    }

    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        BudoElasticsearchJdbcConnection connection = (BudoElasticsearchJdbcConnection) preparedStatement.getConnection();
        TransportClient transportClient = connection.getTransportClient();

        String index = connection.getCatalog();

        ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings = transportClient.admin() //
                .indices() //
                .prepareGetMappings(index) //
                .get() //
                .getMappings();
        String[] columnNames = new String[] { "Name", "Engine", "Comment" };

        List<Map> valueList = new ArrayList<Map>();
        for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> cursor : mappings) {
            ObjectLookupContainer<String> keys = cursor.value.keys();
            for (ObjectCursor<String> objectCursor : keys) {
                valueList.add(MapUtil.stringMap("Name", objectCursor.value, "Engine", "InnoDB", "Comment", ""));
            }
        }

        Map[] valueArray = valueList.toArray(new Map[valueList.size()]);
        MapArrayResultSet resultSet = new MapArrayResultSet(columnNames, valueArray);

        ((BudoElasticsearchJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}